<template>
  <div class="m-header" :style="headerStyle">
    <div class="left">
      <slot name="left"></slot>
    </div>
    <div class="middle" ref="middle">
      <span v-if="notice"
            class="notice"
            ref="notice"
            :class="padding !== 0 ? 'play' : ''"
            :style="noticeStyle"
      >{{ notice }}</span>
      <slot name="middle" />
    </div>
    <div class="right">
      <slot name="right"></slot>
    </div>
  </div>
</template>
<script>
export default {
  props: {
    notice: {
      type: String
    },
    color: {
      type: String,
      default: 'black'
    }
  },
  data() {
    return {
      speed: 30,
      padding: 0
    }
  },
  computed: {
    headerStyle() {
      return {
        color: `${this.color}`
      }
    },
    noticeStyle() {
      const style = {}
      if (this.padding !== 0) {
        style['animation-duration'] = `${this.duration}s`
        style['padding-left'] = `${this.padding}px`
      }
      return style
    },
    middleWidth() {
      return this.$refs.middle.offsetWidth
    },
    duration() {
      return this.middleWidth / this.speed
    }
  },
  methods: {
    play() {
      this.$nextTick(() => {
        this.padding = this.$refs.notice.offsetWidth > this.middleWidth ? this.middleWidth : 0
      })
    }
  },
  watch: {
    notice: {
      handler(value) {
        this.padding = 0
        if (value) {
          this.play()
        }
      },
      immediate: true
    }
  },
  destroyed() {
    clearTimeout(this.timer)
  }
}
</script>
<style lang="less" scoped>
@import '~@/style/variable.less';
.m-header{
  height: 50px;
  display: flex;
  font-size: @font-size-large;
  .middle{
    flex: 1;
    line-height: 50px;
    overflow: hidden;
    .notice{
      display: inline-block;
      white-space: nowrap;
      animation-delay: 0;
    }
  }
  .left,.right{
    display: flex;
    width: 54px;
    justify-content: center;
    align-items: center;
    i{
      font-size: 1em;
    }
  }
}
.play{
  animation: move linear infinite;
}
@keyframes move
{
  to{
    transform: translateX(-100%);
  }
}
</style>